package crossrun.tool.pdf2img.ui.main;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import java.io.File;

import crossrun.tool.pdf2img.R;
import crossrun.tool.pdf2img.adapter.DirListAdapter;

/**
 * A placeholder fragment containing a simple view.
 */
public class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    private PageViewModel pageViewModel;

    public static PlaceholderFragment newInstance(String index) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_SECTION_NUMBER, index);
        fragment.setArguments(bundle);
        return fragment;
    }

    String index;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        pageViewModel = new ViewModelProvider(this).get(PageViewModel.class);
        if (getArguments() != null) {
            index = getArguments().getString(ARG_SECTION_NUMBER);
        }
        pageViewModel.setIndex(getActivity().getExternalFilesDir(index).getAbsolutePath());
    }

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_cache_file, container, false);
        final ListView listView = root.findViewById(R.id.listView);
        pageViewModel.getText().observe(getViewLifecycleOwner(), new Observer<File[]>() {
            @Override
            public void onChanged(@Nullable File[] s) {
                Log.e("top.crossrun","onchange = "+index);
                listView.setAdapter(new DirListAdapter(getContext(),s,index));
            }
        });

        CacheFileViewModel cacheFileViewModel = new ViewModelProvider(getActivity()).get(CacheFileViewModel.class);
        cacheFileViewModel.getRef().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String o) {
                Log.e("top.crossrun","cacheFileViewModel = "+ index);
                if (index.equals(o)){
                    pageViewModel.setIndex(getActivity().getExternalFilesDir(index).getAbsolutePath());
                }
            }
        });

        return root;
    }
}